<?


class CTRLcal extends CONTROL {

	function __construct( $vars ) {
		global $Object, $CAL;
		
		$CAL = new CALENDAR();
		
		$this->_addvars( $vars );
		
		if( $this->action != "list" )
			$this->object = $Object = $this->create_object();
		
	}
	
#	Create object.
	function create_object() {
		global $Object;
		
		//if( $this->type ) $this->vars->type = $this->type;
		
		return $Object = ( $this->action == "new" )?
			new CALNODE( $this->vars, 0, true ): new CALNODE( $this->vars, (int) $this->vars->id );
	
	}
	
#	Object list.
	function filter_list() {
		global $Request;
		
		if( !$this->vars->descr )
			$this->vars->descr = "Calendar overview";
		
		return "
		ref.seed([
			new Element( 'h1' ).update( '{$this->vars->descr}' ),
			lst = new List({ type: ref.vars.type, descr:'" . (( $this->vars->boxdescr )? $this->vars->boxdescr : $this->vars->descr ) . "', blank:'add {$this->vars->type}'})
		]);
		
		lst.seed( ". $Request->parse_list( "ID, ID as key_0, date_format( date, '%d.%m %Y' ) as key_1, substring( <%lang:nameid%>, 1, 42 ) as key_2" ) ." );";
		
	}
	
#	List update.
	function filter_update_list() {
		global $Request;
		
		return "ref.seed( ". $Request->parse_list( "ID, ID as key_0, date_format( date, '%d.%m %Y' ) as key_1, substring( <%lang:nameid%>, 1, 42 ) as key_2" ) ." );";
		
	}
	
#	Edit Object.
	function filter_edit() {
		global $Engine, $Object;
		
		$type = $this->vars->type;
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer '". ( $Object->hasName()? $Object->get( "name" ) : "$type {$Object->id}" ) . "'\" ),
			new Textfield({ descr:'name $type', type:'$type', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Htmlfield({ type:'$type', descr:'info', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "textid" ), 'long' )) ." }),
			new Options({ descr:'Opties', active:1, floats: [
				new Ajxfield({ type:'$type', descr:'Datum', objid:{$Object->id}, field:'date', value:'{$Object->get('date')}', extend:'cal' }),
				new Ajxfield({ type:'$type', descr:'Aantal minuten', objid:{$Object->id}, field:'span', value:'{$Object->get('span')}' }),
				new Shift({ type:'$type', descr:'Is public', value:{$Object->get('active')}, field:'active', objid:{$Object->id} }),
				new Rank({ type:'$type', descr:'Rank', value:{$Object->get('rank')}, field:'rank', objid:{$Object->id} })
			]})
		]);";

	}
	
#	New Object, trough ext:cal.
	function filter_cal_new() {
		global $DB;
		
		if( $this->vars->objid )
			$this->vars->otype = $DB->type( $this->vars->objtype );
		
		
		$Node =  new CALNODE( $this->vars, 0, 1 );
		$this->vars->id = $Node->id;
		
		if( $this->vars->uts )
			$Node->set( "date", date( "Y-m-d H:i:s", (int) $this->vars->uts ));
			
		
		
		return $this->filter_cal_edit();
	}
	
#	Remove Object, trough ext:cal.
	function filter_cal_remove() {
		
		$this->filter_kill();
		
		return "
			$('calendar').info.remove();
			dashboard.comment( 'cleared object.' );
		";
		
	}
	
#	Edit Object.
	function filter_cal_edit() {
		global $Request, $Engine, $DB, $CAL;
		
		$type = $this->vars->type;
		$Object = new CALNODE( "cal.single", (int) $this->vars->id, 0, array( "datestr"=> '%d.%m' ));
		
		if(( $Object->obj && $name = $Object->obj->get( "name" )) || $name = $Object->get( "name" ))
			$name = substr( $Object->get( "datestr" ) . ", $name", 0, 48 );
			
			
		$datespan	= date( "Y-m-d H:i:s", strtotime( $Object->get( "date" ) . " + {$Object->get( "span" )} minutes" ));
		$wday		= date( "D", $Object->timestamp() );
		
		$locs	= $DB->filter_key( "location", "active order by rank desc, llog desc limit 18", "ID as `key`, <%lang:nameid%> as value" );
		$locid	= ( $Object->loc )? $Object->loc->id : ''; 
		
		if(( $event = $Engine->type_exists( "event", "cal.group" )) &&  $eventlist = $CAL->filter( "now()", 356, "cal.single", $event, false, 18 )) {
			
			if( !$parent = $Object->ref_object( 'cal.single', 0 )->id )	$parent = "0";
			
			foreach( $eventlist as $val )
				 $events[] = array( "key" => (int) $val[ "ID" ], "value"=> $val[ "name" ]);
			
			$event = "new Select({ type: '$type', descr:'$event', objid: {$Object->id}, ref:{ parenttype:'cal.single', objtype:'cal.single', parentid:$parent, objid: {$Object->id}, master:0, single:1 }, key:$parent, opts: ". json_encode( $events ) .", func: dashboard.ext.calendar.changetype }),";
		
		} else $event = "";
		
		return "
		ref.dayseed( '$name', [
			new Ajxfield({ type: '$type', descr:'van', objid: {$Object->id}, field:'date', value:'". $Object->get( "date" ) ."', ext:'cal' }),
			new Ajxfield({ type: '$type', descr:'tot', objid: {$Object->id}, field:'date', value:'$datespan', ext:'cal', func: dashboard.ext.calendar.calcspan  }),
			new Select({ type: '$type', descr:'locatie', objid: {$Object->id}, field:'location', key: '$locid', opts: " . json_encode( $locs ) . " }), 
			$event br,
			new Textfield({ type:'$type', descr:'titel', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Htmlfield({ type:'$type', descr:'info', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", values:". json_encode( $Engine->text->filter( $Object->get( "textid" ), 'long' )) ." }),
			new Ajxfield({ type:'$type', descr:'link', objid:{$Object->id}, field:'meta.url', value: '". $Object->get( "url" ) ."' }),
			new Rank({ type:'$type', descr:'Rank', value:{$Object->get('rank')}, field:'rank', objid:{$Object->id} })
		], [
			new Element( 'div', { class:'day' }).update( '$wday' ),
			new Shift({ type: '$type', descr:'Is public', value:{$Object->get( "active")}, field:'active', objid:{$Object->id} }),
			new Shift({ type: '$type', descr:'In listed', value:". (((int) $Object->get( "active" ) == 2)? 0 : 1) .", options:[2,1], field:'active', objid:{$Object->id} }),
			br, br, br,
			new Button({ action: 'cal_new', type: '$type', descr: 'new', class: 'smallbutton', vars: { type:'$type', uts: {$Object->timestamp()}}}),
			new Button({ action: 'cal_remove', type: '$type', descr: 'delete', class: 'smallbutton', id:{$Object->id} })
		] );";
		
	}
	
#	Load object reference.
	function filter_cal_load_object() {
		global $Request, $Engine, $DB, $CAL;
		
		
	}

#	Seed Calendar.
	function filter_seed() {
		global $Request, $Engine, $DB, $CAL;
		
		if( $Request->id ) {
		
			$Object =  new OBJECT( $Request->objtype, $Request->id );
		
			/*if( $dates = $CAL->filter_nodes_by_object( "cal.single", $Object->type, $Object->id, true )) {

				foreach( $dates as $Node )
					$nodes[] = "new button({ action: 'cal_edit', type: 'cal.single', descr:'{$Node->date('d.m y')}', vars: {objtype:'{$Node->type}',id:{$Node->id}}})";
				
				$reset = strtotime( date( "Y-m-01", (int) $dates[0]["day"] ));
			}*/
			
			$objseed = "
				ref.objhook	= { type:'{$Object->type}', id:{$Object->id}};
				ref.addlist( '{$Object->get('name')} in calendar', ". json_encode( $nodes ) .", 1, 'addnew' );
			";			
		}
		
		$calc = $this->calc_hook( $reset );
		
		if( $group = $DB->filter_key( "cal.single", "datediff(date, from_unixtime({$calc->hook})) > -7 && datediff(date, from_unixtime({$calc->hook})) < 46 order by day", "ID, unix_timestamp(date(date)) as day, date_format(date, '%k:%i') as time, objid, type" ))
			foreach( $group as $row ) $dates[ $row[ "day" ]][] = $row;
		
		return "
			ref.seed(". json_encode($dates) .",{ year:{$calc->date['year']}, month:" .( $calc->date['mon']-1 ). ", day:" .( $calc->date["mday"] -$calc->diff ). ", monthstring:'{$calc->date['month']} {$calc->date['year']}' });
			$objseed
		";

	}

#	Calculate current calendarview
	function calc_hook( $reset ) {
		global $Request;
		
		$calc = (object) array();
		
		$calc->hook	= ( $reset )? $reset : strtotime( date( "Y-m-01" ) . (( $Request->vars->hook<0)? "":"+" ) . $Request->vars->hook . " month" );
		$calc->diff	= date( "N", $calc->hook ) -1;
		$calc->date	= getdate( $calc->hook );
	
		return $calc;
	}
	
	
#	Day node.
	function filter_day() {
		global $Request, $Engine, $DB;
		
		if( !$Request->id ) {
			$vars = array( "date"=> date( "Y-m-d 12:00:00", ( int ) $Request->day ), "span"=> 30, "rank"=> 5, "active"=> 0, "flog"=> date( "Y-m-d H:m:s" ), "creator"=> $Engine->user() );
			if( $Request->vars->id )
				$vars = array_merge( $vars, array( "otype"=> $DB->type( $Request->vars->objtype ), "objid"=> $Request->vars->id ));
			
			$Request->id = $DB->set( "cal.single", $vars, false, true );
		}
		
		$date = $DB->get( "cal.single", (int) $Request->id,
			"*, ID as id, date_format( date, '%d.%m' ) as descr, date_format( date, '%M %e, %Y') as name, date_format( date, '%a') as wday, ( date + interval span minute ) as datespan, unix_timestamp(date(date)) as day"
		);
		
		if( $result = $DB->filter_key( "location", "active order by rank desc limit 24", "ID, <%lang:nameid%> as name" ))
			foreach( $result as $node ) $locations[ htmlentities( $node[ "name" ])] = $node["ID"] ;
		
		
		$date[ "short" ]	= $Engine->text->filter( (int) $date[ "nameid" ] );
		$date[ "long" ]		= $Engine->text->filter( (int) $date[ "textid" ], "long" );
		$date[ "locs" ]		= $locations;
		$date[ "meta" ]		= ( $date[ "meta" ] )? json_decode( $date[ "meta" ]) : array();
		
				
		return "ref.dayseed(" . json_encode( $date ). ")";

	}

}


?>